<?php

namespace app\common\model;

use think\Model;
use think\Validate;

class Admin extends Model
{

    /**
     * 登录验证
     *
     * @param $post
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login($post)
    {
        $validate = new Validate([
            'username|用户名' => 'require',
            'password|密码' => 'require',
            'captcha|验证码' => 'require|captcha'
        ]);
        if (!$validate->check($post)) {
            return ['code' => 0, 'message' => $validate->getError()];
        }
        $user = $this->where('username', $post['username'])->find();
        if (!$user) {
            return ['code' => 0, 'message' => '用户名不正确'];
        }
        if (!password_verify($post['password'], $password = $user['password'])) {
            return ['code' => 0, 'message' => '密码不正确'];
        }
        session('admin.id', $user['id']);
        session('admin.username', $user['username']);
        session('admin.nickname', $user['nickname']);
        return ['code' => 1, 'message' => '登录成功'];
    }

    /*
     * 获取管理员信息
     */
    /**
     * @return Admin|null
     * @throws \think\Exception\DbException
     */
    public function getInfo()
    {
        $info = $this->get(session('admin.id'));
        return $info;
    }

    /**
     * 修改密码
     *
     * @param $post
     *
     * @return array
     * @throws \think\Exception\DbException
     */
    public function change($post)
    {
        $validate = new Validate([
            'password|密码' => 'require|confirm|min:6'
        ]);
        if (!$validate->check($post)) {
            return ['code' => 0, 'message' => $validate->getError()];
        }
        $user = $this->get($post['id']);
        $user->password = password_hash($post['password'], PASSWORD_DEFAULT);
        $user->save();

        return ['code' => 1, 'message' => '密码修改成功'];
    }
}
